package com.cleaningcloud.erp.service.impl;

import com.cleaningcloud.common.core.exception.ServiceException;
import com.cleaningcloud.common.core.utils.DateUtils;
import com.cleaningcloud.common.core.utils.SecretUtil;
import com.cleaningcloud.common.core.utils.StringUtils;
import com.cleaningcloud.common.security.utils.CommunityTypeConversionUtils;
import com.cleaningcloud.common.security.utils.SecurityUtils;
import com.cleaningcloud.erp.api.domain.ErpCommodity;
import com.cleaningcloud.erp.domain.ErpCommodityUnit;
import com.cleaningcloud.erp.domain.ErpSupplierCommodity;
import com.cleaningcloud.erp.domain.dto.ErpCommodityDto;
import com.cleaningcloud.erp.domain.vo.ErpCommodityVo;
import com.cleaningcloud.erp.domain.vo.ErpSupplierCommodityVo;
import com.cleaningcloud.erp.mapper.ErpCommodityMapper;
import com.cleaningcloud.erp.mapper.ErpCommodityUnitMapper;
import com.cleaningcloud.erp.mapper.ErpSupplierCommodityMapper;
import com.cleaningcloud.erp.service.IErpCommodityService;
import com.cleaningcloud.erp.service.IErpSupplierCommodityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 供应商商品Service业务层处理
 *
 * @author cleaningcloud
 * @date 2024-09-26
 */
@Service
public class ErpSupplierCommodityServiceImpl implements IErpSupplierCommodityService {

    private static final Logger log = LoggerFactory.getLogger(ErpSupplierCommodityServiceImpl.class);

    @Autowired
    private ErpSupplierCommodityMapper erpSupplierCommodityMapper;

    @Autowired
    private ErpCommodityMapper erpCommodityMapper;

    @Autowired
    private IErpCommodityService commodityService;

    @Autowired
    private ErpCommodityUnitMapper erpCommodityUnitMapper;

    /**
     * 查询供应商商品
     *
     * @param supplierCommodityId 供应商商品主键
     * @return 供应商商品
     */
    @Override
    public ErpSupplierCommodity selectErpSupplierCommodityBySupplierCommodityId(Long supplierCommodityId) {
        return erpSupplierCommodityMapper.selectErpSupplierCommodityBySupplierCommodityId(supplierCommodityId);
    }

    /**
     * 查询供应商商品列表
     *
     * @param erpSupplierCommodity 供应商商品
     * @return 供应商商品
     */
    @Override
    public List<ErpSupplierCommodityVo> selectErpSupplierCommodityList(ErpSupplierCommodity erpSupplierCommodity) {
        //erpSupplierCommodity.setSupplierCommodityType(CommunityTypeConversionUtils.conversionRegexp(erpSupplierCommodity.getSupplierCommodityType()));
        List<ErpSupplierCommodityVo> list = erpSupplierCommodityMapper.selectErpSupplierCommodityList(erpSupplierCommodity);
        for (ErpSupplierCommodityVo supplierCommodityVo : list) {
            supplierCommodityVo.setCommodityTypeName(CommunityTypeConversionUtils.conversion(supplierCommodityVo.getSupplierCommodityType()));
        }
        return list;
    }

    /**
     * 新增供应商商品
     *
     * @param erpSupplierCommodity 供应商商品
     * @return 结果
     */
    @Override
    @Transactional
    public int insertErpSupplierCommodity(ErpSupplierCommodity erpSupplierCommodity) {
        int check = erpSupplierCommodityMapper.checkNoUnique(erpSupplierCommodity.getSupplierCommodityNo(), erpSupplierCommodity.getSupplierId());
        if (check > 0) {
            throw new RuntimeException("商品编号`" + erpSupplierCommodity.getSupplierCommodityNo() + "`已存在！");
        }
        if (StringUtils.isNotEmpty(erpSupplierCommodity.getSupplierCommodityImgtext())) {
            erpSupplierCommodity.setSupplierCommodityImgtext(SecretUtil.desEncrypt(erpSupplierCommodity.getSupplierCommodityImgtext(), SecretUtil.KEY, SecretUtil.IV));
        }
        erpSupplierCommodity.setCreateTime(DateUtils.getNowDate());
        erpSupplierCommodity.setCreateId(SecurityUtils.getUserId());
        erpSupplierCommodity.setCreateName(SecurityUtils.getUsername());
        erpSupplierCommodity.setFlag("Y");
        // 根据供应商商品编号查询库存商品
        Long commodityId = erpCommodityMapper.selectCommodityByNo(erpSupplierCommodity.getSupplierCommodityNo());
        if (commodityId == null) {
            // 新增库存商品
            ErpCommodityDto erpCommodity = new ErpCommodityDto();
            erpCommodity.setCommodityNo(erpSupplierCommodity.getSupplierCommodityNo());
            erpCommodity.setCommodityName1(erpSupplierCommodity.getSupplierCommodityName());
            erpCommodity.setCommodityName2(erpSupplierCommodity.getSupplierCommodityName());
            erpCommodity.setCommodityType(erpSupplierCommodity.getSupplierCommodityType());
            erpCommodity.setCommodityDescribe(erpSupplierCommodity.getSupplierCommodityDescribe());
            erpCommodity.setCommodityBrand(erpSupplierCommodity.getSupplierCommodityBrand());
            erpCommodity.setCommoditySpec(erpSupplierCommodity.getSupplierCommoditySpec());
            erpCommodity.setCommodityImg(erpSupplierCommodity.getSupplierCommodityImg());
            erpCommodity.setCommodityImgtext(erpSupplierCommodity.getSupplierCommodityImgtext());
            erpCommodity.setCommodityStatus(1L);
            List<ErpCommodityUnit> unitList = new ArrayList<>();
            ErpCommodityUnit unit = new ErpCommodityUnit();
            unit.setUnitName1(erpSupplierCommodity.getSupplierCommodityUnit());
            unit.setUnitName2(erpSupplierCommodity.getSupplierCommodityUnit());
            unit.setCostPrice(erpSupplierCommodity.getSupplierCommodityQuotation());
            unit.setUnitResult(1L);
            unit.setUnitRelationship("1" + erpSupplierCommodity.getSupplierCommodityUnit() + "=1" + erpSupplierCommodity.getSupplierCommodityUnit());
            unitList.add(unit);
            erpCommodity.setUnitList(unitList);
            commodityService.insertErpCommodity(erpCommodity);
            commodityId = erpCommodityMapper.selectCommodityByNo(erpSupplierCommodity.getSupplierCommodityNo());
        }
        erpSupplierCommodity.setCommodityId(commodityId);
        return erpSupplierCommodityMapper.insertErpSupplierCommodity(erpSupplierCommodity);
    }

    /**
     * 修改供应商商品
     *
     * @param erpSupplierCommodity 供应商商品
     * @return 结果
     */
    @Override
    public int updateErpSupplierCommodity(ErpSupplierCommodity erpSupplierCommodity) {
        if (StringUtils.isNotEmpty(erpSupplierCommodity.getSupplierCommodityImgtext())) {
            erpSupplierCommodity.setSupplierCommodityImgtext(SecretUtil.desEncrypt(erpSupplierCommodity.getSupplierCommodityImgtext(), SecretUtil.KEY, SecretUtil.IV));
        }
        // 根据供应商商品编号查询库存商品
        Long commodityId = erpCommodityMapper.selectCommodityByNo(erpSupplierCommodity.getSupplierCommodityNo());
        if (commodityId == null) {
            throw new RuntimeException("商品查询失败,请检查商品编码！");
        }
        erpSupplierCommodity.setCommodityId(commodityId);
        return erpSupplierCommodityMapper.updateErpSupplierCommodity(erpSupplierCommodity);
    }

    /**
     * 批量删除供应商商品
     *
     * @param supplierCommodityIds 需要删除的供应商商品主键
     * @return 结果
     */
    @Override
    public int deleteErpSupplierCommodityBySupplierCommodityIds(Long[] supplierCommodityIds) {
        return erpSupplierCommodityMapper.deleteErpSupplierCommodityBySupplierCommodityIds(supplierCommodityIds);
    }

    /**
     * 删除供应商商品信息
     *
     * @param supplierCommodityId 供应商商品主键
     * @return 结果
     */
    @Override
    public int deleteErpSupplierCommodityBySupplierCommodityId(Long supplierCommodityId) {
        return erpSupplierCommodityMapper.deleteErpSupplierCommodityBySupplierCommodityId(supplierCommodityId);
    }

    @Override
    @Transactional
    public String importErpSupplierCommodity(List<ErpCommodityVo> commodityList, Boolean isUpdateSupport, String operName, Long supplierId) {
        if (StringUtils.isNull(commodityList) || commodityList.size() == 0) {
            throw new ServiceException("导入商品数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (ErpCommodityVo excelImport : commodityList) {
            try {
                // 验证是否存在这个商品
                ErpSupplierCommodity supplierCommodity = erpSupplierCommodityMapper.selectErpSupplierCommodityBySupplierCommodityNo(excelImport.getCommodityNo(),supplierId);
                // 根据供应商商品编号查询库存商品
                Long commodityId = erpCommodityMapper.selectCommodityByNo(excelImport.getCommodityNo());
                ErpSupplierCommodity erpSupplierCommodity = new ErpSupplierCommodity();
                if (StringUtils.isNull(supplierCommodity)) {
                    erpSupplierCommodity.setSupplierId(supplierId);
                    erpSupplierCommodity.setCreateTime(DateUtils.getNowDate());
                    erpSupplierCommodity.setCreateId(SecurityUtils.getUserId());
                    erpSupplierCommodity.setCreateName(SecurityUtils.getUsername());
                    erpSupplierCommodity.setSupplierCommodityNo(excelImport.getCommodityNo());
                    erpSupplierCommodity.setSupplierCommodityBrand(excelImport.getCommodityBrand());
                    erpSupplierCommodity.setSupplierCommodityDescribe(excelImport.getCommodityDescribe());
                    erpSupplierCommodity.setSupplierCommodityName(excelImport.getCommodityName1());
                    erpSupplierCommodity.setSupplierCommoditySpec(excelImport.getCommoditySpec());
                    erpSupplierCommodity.setSupplierCommodityType(excelImport.getCommodityTypeId());
                    erpSupplierCommodity.setSupplierCommodityUnit(excelImport.getUnitName1());
                    erpSupplierCommodity.setSupplierCommodityQuotation(excelImport.getCostPrice());
                    erpSupplierCommodity.setFlag("Y");
                    if (commodityId == null) {
                        // 新增库存商品
                        ErpCommodity erpCommodity = new ErpCommodity();
                        BeanUtils.copyProperties(excelImport, erpCommodity);
                        erpCommodity.setCreateTime(DateUtils.getNowDate());
                        erpCommodity.setCreateId(SecurityUtils.getUserId());
                        erpCommodity.setCreateName(SecurityUtils.getUsername());
                        erpCommodity.setFlag("Y");
                        erpCommodity.setCommodityStatus(1L);
                        erpCommodity.setCommodityType(erpCommodity.getCommodityTypeId());
                        erpCommodityMapper.insertErpCommodity(erpCommodity);
                        // 添加商品单位
                        ErpCommodityUnit erpCommodityUnit = new ErpCommodityUnit();
                        erpCommodityUnit.setUnitName1(excelImport.getUnitName1());
                        if (StringUtils.isNotEmpty(excelImport.getUnitName2())) {
                            erpCommodityUnit.setUnitName2(excelImport.getUnitName2());
                        } else {
                            if (StringUtils.isNotEmpty(excelImport.getUnitName1())) {
                                erpCommodityUnit.setUnitName2(excelImport.getUnitName1());
                            }
                        }
                        erpCommodityUnit.setUnitResult(excelImport.getUnitResult() == null ? 1 : excelImport.getUnitResult());
                        erpCommodityUnit.setCostPrice(excelImport.getCostPrice());//成本价
                        erpCommodityUnit.setSymbolPrice(excelImport.getSymbolPrice());//胜博价
                        erpCommodityUnit.setRetailPrice(excelImport.getRetailPrice());//零售价
                        erpCommodityUnit.setDistriPrice(excelImport.getDistriPrice());//经销价
                        erpCommodityUnit.setAgencyPrice(excelImport.getAgencyPrice());//代理价
                        if (StringUtils.isEmpty(excelImport.getUnitRelationship())) {
                            erpCommodityUnit.setUnitRelationship("1" + excelImport.getUnitName1() + "=" + excelImport.getUnitResult() + excelImport.getUnitName2());
                        } else {
                            erpCommodityUnit.setUnitRelationship(excelImport.getUnitRelationship());
                        }
                        erpCommodityUnit.setCommodityId(erpCommodity.getCommodityId());
                        erpCommodityUnitMapper.insertErpCommodityUnit(erpCommodityUnit);
                        erpCommodity.setCommodityUnitId(erpCommodityUnit.getCommodityUnitId());
                        commodityId = erpCommodity.getCommodityId();
                        erpCommodityMapper.updateErpCommodity(erpCommodity);
                    }
                    erpSupplierCommodity.setCommodityId(commodityId);
                    erpSupplierCommodityMapper.insertErpSupplierCommodity(erpSupplierCommodity);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、商品编号 " + excelImport.getCommodityNo() + " 导入成功");
                } else if (isUpdateSupport) {
                    erpSupplierCommodity.setSupplierCommodityId(supplierCommodity.getSupplierCommodityId());
                    erpSupplierCommodity.setCommodityId(commodityId);
                    erpSupplierCommodityMapper.updateErpSupplierCommodity(erpSupplierCommodity);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、商品编号 " + excelImport.getCommodityNo() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、商品编号 " + excelImport.getCommodityNo() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、商品编号 " + excelImport.getCommodityNo() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
